<template>
    <div class="p-2">
        <transition
            :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave"
        >
            <div v-show="showSearch" class="mb-[10px]">
                <el-card shadow="hover">
                    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                        <el-form-item label="组织名称" prop="deptName">
                            <el-input
                                v-model.trim="queryParams.deptName"
                                placeholder="请输入组织名称"
                                clearable
                                @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="类别编码" prop="deptCategory">
                            <el-input
                                v-model.trim="queryParams.deptCategory"
                                placeholder="请输入类别编码"
                                clearable
                                style="width: 240px"
                                @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="queryParams.status" placeholder="组织状态" clearable>
                                <el-option
                                    v-for="dict in sys_normal_disable"
                                    :key="dict.value"
                                    :label="dict.label"
                                    :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
                            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>
        </transition>

        <el-card shadow="hover">
            <template #header>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button
                            v-hasPermi="['system:dept:add']"
                            type="primary"
                            plain
                            :icon="Plus"
                            @click="handleAdd()"
                            >新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="info" plain :icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain :icon="UploadFilled" :loading="syncLoading" @click="syncData"
                            >数据同步</el-button
                        >
                    </el-col>
                    <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table
                ref="deptTableRef"
                v-loading="loading"
                :data="deptList"
                row-key="deptId"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                :default-expand-all="isExpandAll"
            >
                <el-table-column prop="deptName" label="组织名称" width="260"></el-table-column>
                <el-table-column prop="deptType" align="center" label="组织类型" width="100">
                    <template #default="scope">
                        <dict-tag
                            :options="[
                                { label: '公司', value: '0', elTagType: 'primary', elTagClass: 'el-tag--dark' },
                                { label: '公司', value: '1', elTagType: 'primary', elTagClass: 'el-tag--light' },
                                { label: '部门', value: '2', elTagType: 'info', elTagClass: 'el-tag--plain' }
                            ]"
                            :value="scope.row.deptType"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="orderNum" align="center" label="排序" width="200"></el-table-column>
                <el-table-column prop="status" align="center" label="状态" width="100">
                    <template #default="scope">
                        <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime" width="200">
                    <template #default="scope">
                        <span>{{ proxy.parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" align="center" label="操作">
                    <template #default="scope">
                        <el-tooltip content="修改" placement="top">
                            <el-button
                                v-hasPermi="['system:dept:edit']"
                                link
                                type="primary"
                                :icon="Edit"
                                @click="handleUpdate(scope.row)"
                            />
                        </el-tooltip>
                        <el-tooltip content="新增" placement="top">
                            <el-button
                                v-hasPermi="['system:dept:add']"
                                link
                                type="primary"
                                :icon="Plus"
                                @click="handleAdd(scope.row)"
                            />
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button
                                v-hasPermi="['system:dept:remove']"
                                link
                                type="primary"
                                :icon="Delete"
                                @click="handleDelete(scope.row)"
                            />
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-dialog v-model="dialog.visible" :title="dialog.title" destroy-on-close append-to-body width="600px">
            <el-form ref="deptFormRef" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="组织类型" v-if="deptInfo.deptId">
                            <el-radio-group v-model="form.deptType">
                                <el-radio value="0" v-if="form.parentId == 0">总公司</el-radio>
                                <el-radio value="1" v-if="deptInfo.deptType == '0'">子公司</el-radio>
                                <el-radio value="2">部门</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="form.parentId !== 0" :span="24">
                        <el-form-item
                            :label="deptInfo.deptId ? (deptInfo.deptType != '2' ? '所属公司' : '所属部门') : '所属组织'"
                            prop="parentId"
                        >
                            <el-tree-select
                                v-model="form.parentId"
                                :data="deptOptions"
                                :props="{ value: 'deptId', label: 'deptName', children: 'children' } as any"
                                value-key="deptId"
                                placeholder="选择上级部门"
                                check-strictly
                                :disabled="dialog?.title?.substring(0, 2) == '添加' || isCompany"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="isCompany ? '公司名称' : '部门名称'" prop="deptName">
                            <el-input
                                v-model.trim="form.deptName"
                                @blur="generateJianpin"
                                :placeholder="isCompany ? '请输入公司名称（简称）' : '请输入部门名称'"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="公司ID" prop="deptId" v-if="isCompany">
                            <el-input v-model.trim="form.deptId" placeholder="自动生成" :disabled="true" />
                        </el-form-item>
                        <el-form-item label="类别编码" prop="deptCategory" v-else>
                            <el-input v-model.trim="form.deptCategory" placeholder="请输入类别编码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="isCompany">
                        <el-form-item label="公司全称" prop="deptFullName">
                            <el-input v-model.trim="form.deptFullName" placeholder="请输入公司全称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="isCompany">
                        <el-form-item label="公司简拼" prop="deptBriefName">
                            <el-input v-model.trim="form.deptBriefName" placeholder="请输入公司简拼" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系人" prop="contactPerson" v-if="isCompany">
                            <el-input v-model.trim="form.contactPerson" placeholder="请输入联系人" />
                        </el-form-item>
                        <el-form-item label="负责人" prop="leader" v-else>
                            <el-select v-model="form.leader" placeholder="请选择负责人">
                                <el-option
                                    v-for="item in deptUserList"
                                    :key="item.userId"
                                    :label="item.userName"
                                    :value="item.userId"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="phone">
                            <el-input v-model.trim="form.phone" placeholder="请输入联系电话" maxlength="11" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="!isCompany">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model.trim="form.email" placeholder="请输入邮箱" maxlength="50" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="isCompany">
                        <el-form-item label="公司地址" prop="companyAddress">
                            <el-input
                                v-model.trim="form.address"
                                maxlength="200"
                                show-word-limit
                                placeholder="请输入地址"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态">
                            <el-radio-group v-model="form.status">
                                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{
                                    dict.label
                                }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="显示排序" prop="orderNum">
                            <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="isCompany">
                        <el-form-item label="描述" prop="description">
                            <el-input
                                v-model.trim="form.description"
                                maxlength="200"
                                show-word-limit
                                placeholder="请输入描述"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Dept" lang="ts">
import type { DeptForm, DeptQuery, DeptVO, UserVO, CompanyVO } from '@great/services';
import { systemUserService, systemDeptService, systemCompanyService } from '@great/services';
import RightToolbar from '@/pages/system/user/components/RightToolbar.vue';
import DictTag from '@/pages/system/user/components/DictTag.vue';
import { Refresh, Delete, Edit, Plus, Search, Sort, UploadFilled } from '@element-plus/icons-vue';
import type { DialogOption, ElFormInstance, ElTableInstance, PageData, ElTreeInstance } from '@/pages/system/system.d';
import { getPinyinInitials } from '@/utils/ruoyi';

interface DeptOptionsType {
    deptId: number | string;
    deptName: string;
    children: DeptOptionsType[];
}

const { proxy } = getCurrentInstance() as any;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const deptList = ref<DeptVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const deptOptions = ref<DeptOptionsType[]>([]);
const deptInfo = ref<DeptVO>({} as DeptVO);
const isExpandAll = ref(true);
const deptUserList = ref<UserVO[]>([]);

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const deptTableRef = ref<ElTableInstance>();
const queryFormRef = ref<ElFormInstance>();
const deptFormRef = ref<ElFormInstance>();

const initFormData: DeptForm = {
    deptId: undefined,
    parentId: undefined,
    deptName: undefined,
    deptCategory: undefined,
    deptBriefName: undefined,
    deptCode: undefined,
    deptFullName: undefined,
    orderNum: 0,
    leader: undefined,
    contactPerson: undefined,
    phone: undefined,
    email: undefined,
    status: '0',
    address: undefined,
    description: undefined,
    deptType: ''
};
const initData: PageData<DeptForm, any> = {
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptName: undefined,
        deptCategory: undefined,
        status: undefined,
        companyCode: undefined
    },
    rules: {
        parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
        deptName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
        email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
        phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
    }
};
const data = reactive<PageData<DeptForm, DeptQuery>>(initData);

const { queryParams, form, rules } = toRefs<PageData<DeptForm, DeptQuery>>(data);

/**
 * 递归查找树形结构中的根节点(parentId为0的节点)
 * @param {Array} nodes - 树形结构数组
 * @param {number} curNode - 开始查找的节点
 * @returns {Object|null} - 找到的根节点或null
 */
const nodeMap = new Map(); // 递归遍历所有节点，创建完整的节点映射表
function findRootNode(nodes, curNode, keyName = 'deptId') {
    // 递归遍历树形结构，收集所有节点
    function traverseTree(treeNodes, disabled = false) {
        treeNodes.forEach(node => {
            if (node[keyName] !== undefined) {
                nodeMap.set(node[keyName], node);
                node.disabled = disabled || node.disabled;
            }

            // 如果有children，递归遍历子节点
            if (node.children && Array.isArray(node.children)) {
                traverseTree(node.children, node.disabled);
            }
        });
    }
    if (nodeMap.size === 0) {
        // 开始遍历整棵树
        traverseTree(nodes);
    }

    // 递归查找父节点
    function findParent(current, curKeyId = 'parentId') {
        const parentNode = nodeMap.get(current[curKeyId]);
        if (!parentNode) {
            return current.deptType == '0' ? [current] : []; // 没有父节点， 当前是总公司返回当前节点
        }

        // 如果parentId为0，说明找到了根节点
        if (parentNode.parentId === 0 || !nodeMap.has(parentNode[curKeyId])) {
            if (parentNode.deptType == '0') {
                if (current.deptType == '1') {
                    return [parentNode, current]; // 总公司及子公司都返回了
                }
                return [parentNode]; // 只返回总公司节点
            }
            return [];
        }

        // 继续查找父节点
        return findParent(parentNode);
    }

    if (!curNode || !nodeMap.get(curNode[keyName])) return []; // 当前传入节点异常的情况
    if (curNode.deptType == '0') return [curNode]; // 当前就是根节点，直接返回当前节点

    // 从指定节点开始查找
    return findParent(curNode);
}

// 根据简称生成简拼
const generateJianpin = () => {
    form.value.deptBriefName = getPinyinInitials(form.value.deptName);
};

/** 查询菜单列表 */
const getList = async () => {
    loading.value = true;
    const res = await systemDeptService.listDept(queryParams.value);
    const data = proxy?.handleTree(res.data, 'deptId');
    if (data) {
        deptList.value = data;
    }
    loading.value = false;
};

/** 查询当前部门的所有用户 */
async function getDeptAllUser(deptId: any) {
    if (deptId !== null && deptId !== '' && deptId !== undefined) {
        const res = await systemUserService.listUserByDeptId(deptId);
        deptUserList.value = res.data;
    }
}

/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
};
/** 表单重置 */
const reset = () => {
    form.value = { ...initFormData };
    deptFormRef.value?.resetFields();
    deptOptions.value = [];
    deptInfo.value = {} as DeptVO;
};

/** 搜索按钮操作 */
const handleQuery = () => {
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

/** 同步数据 */
const syncLoading = ref(false);
const syncData = async () => {
    syncLoading.value = true;
    const res = await systemDeptService.syncData();
    syncLoading.value = false;
    if (res.code == '200') {
        ElMessage({ type: 'success', message: '同步成功' });
    } else {
        ElMessage({ type: 'error', message: res.msg });
    }
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
    isExpandAll.value = !isExpandAll.value;
    toggleExpandAll(deptList.value, isExpandAll.value);
};
/** 展开/折叠所有 */
const toggleExpandAll = (data: DeptVO[], status: boolean) => {
    data.forEach(item => {
        deptTableRef.value?.toggleRowExpansion(item, status);
        if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
    });
};

const isCompany = computed(() => {
    if (form.value?.deptType == '0' || form.value?.deptType == '1') {
        return true;
    }
    return false;
});

/** 新增按钮操作 */
const handleAdd = async (row?: DeptVO) => {
    reset();
    const company = findRootNode(deptList.value, row);
    console.log('当前节点的总公司', company[0]?.deptName, '子公司', company[1]?.deptName);
    deptOptions.value = deptList.value; // 添加不可切换所属关系，这里是禁用状态，所有传全部树过去
    if (row) {
        // 列表内添加部门或子公司
        deptInfo.value = row;
        if (row.deptId) {
            form.value.parentId = row?.deptId;
            /**
             * 前端找到的集团及子公司节点,后台自己找了，先去掉
             * form.value.companyDeptId = company && company[0]?.deptId || 0;
             * form.value.subCompanyDeptId = company && company[1]?.deptId || 0;
             */
        }
        if (row.deptType == '2' || row.deptType == '1') {
            // 部门及子公司下只能建部门
            form.value.deptType = '2';
        }
    } else {
        // 新增集团公司
        form.value.deptType = '0'; // 公司
        form.value.parentId = 0;
    }
    dialog.visible = true;
    dialog.title = `${row ? (row.deptType != '0' ? '添加部门' : '添加组织') : '新建公司'}`;
};

/** 修改按钮操作 */
const handleUpdate = async (row: DeptVO) => {
    reset();
    //查询当前部门所有用户
    getDeptAllUser(row.deptId);
    const res = await systemDeptService.getDept(row.deptId); // 查询部门详情信息
    form.value = res.data;
    const response = await systemDeptService.listDeptExcludeChild(row.deptId); // 查询部门下拉树结构（排除节点）
    const data = proxy?.handleTree(response.data, 'deptId');
    if (data) {
        deptOptions.value = data.filter(val => val.deptId == res.data.companyDeptId); // 过滤出当前公司下的树结构
        if (data.length === 0) {
            const noResultsOptions: DeptOptionsType = {
                deptId: res.data.parentId,
                deptName: res.data.parentName,
                children: []
            };
            deptOptions.value.push(noResultsOptions);
        }
    }
    dialog.visible = true;
    dialog.title = `修改${row.deptType == '2' ? '部门' : '公司'}`;
};
/** 提交按钮 */
const submitForm = () => {
    deptFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            form.value.deptId
                ? await systemDeptService.updateDept(form.value)
                : await systemDeptService.addDept(form.value);
            proxy?.$modal.msgSuccess('操作成功');
            dialog.visible = false;
            await getList();
        }
    });
};
/** 删除按钮操作 */
const handleDelete = async (row: DeptVO) => {
    await proxy?.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?');
    await systemDeptService.delDept(row.deptId);
    await getList();
    proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
    getList();
});
</script>
